<template>
    <div class="goods-model">
      <div class="view-box">
        <div class="goods-list">
          <div class="btns">
            <el-button @click="editGoods('null')" type="warning">+发布商品</el-button>
            <el-button type="primary" v-show="currentType==='depot'||currentType==='soldout'" @click="shelves('sale')" >批量上架</el-button>
            <el-button type="primary" v-show="currentType==='all'||currentType==='sale'" @click="shelves('depot')" >批量下架</el-button>
            <el-button type="primary" @click="setGroup">设置分组</el-button>
          </div>
          <div class="search-box clearfix">
            <div class="labelName lf">商品名称：</div><el-input class="elInput lf" v-model="goodsName"></el-input>
            <div class="labelName lf">所属类别：</div>
            <div class="cascader lf">
              <el-cascader expand-trigger="click" :options="typeOptions" v-model="gtid" :change-on-select="true"></el-cascader>
            </div>
            <div class="labelName lf">所属分组：</div>
            <div class="cascader lf">
              <el-cascader expand-trigger="click" :options="searchOptions" v-model="gpid" :change-on-select="true"></el-cascader>
            </div>
            <!--<el-input class="elInput lf" v-model="groupId"></el-input>-->
            <div class="labelName lf">更新时间：</div>
            <el-date-picker class="lf elInput" style="margin-right:10px;"  value-format="yyyy-MM-dd 00:00:00" v-model="startTime" type="date" placeholder="选择日期"></el-date-picker>
            <div class="labelName lf">至：</div>
            <el-date-picker value-format="yyyy-MM-dd 23:59:59" class="elInput lf" v-model="endTime" type="date" placeholder="选择日期"></el-date-picker>
            <el-button class="lf" type="primary" @click="searchData()">查询</el-button>
          </div>

          <div class="table-box">
            <el-table :data="goodsList" @selection-change="clickRow">
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column label="商品" width="250">
                <template slot-scope="scope">
                  <div class="goodsDetail clearfix">
                    <img class="lf" :src="scope.row.image" alt="">
                    <span class="lf">{{scope.row.goods_name}}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="成本价">
                <template slot-scope="scope">
                  <div class="price">
                    {{scope.row.min_supply_price===scope.row.max_supply_price?scope.row.max_supply_price:scope.row.min_supply_price+"~"+scope.row.max_supply_price}}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="零售价">
                <template slot-scope="scope">
                  <div class="price">
                    {{scope.row.min_sell_price===scope.row.max_sell_price?scope.row.max_sell_price:scope.row.min_sell_price+"~"+scope.row.max_sell_price}}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="玩购价">
                <template slot-scope="scope">
                  <div class="price">
                    {{scope.row.min_play_price===scope.row.max_play_price?scope.row.max_play_price:scope.row.min_play_price+"~"+scope.row.max_play_price}}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="星星价">
                <template slot-scope="scope">
                  <div class="price">
                    {{scope.row.min_star_price===scope.row.max_star_price?scope.row.max_star_price:scope.row.min_star_price+"~"+scope.row.max_star_price}}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="库存" prop="stock"></el-table-column>
              <el-table-column label="兑换库存" prop="exchange_stock"></el-table-column>
              <el-table-column label="销量" prop="sale_num"></el-table-column>
              <el-table-column label="来源" prop="gs_name"></el-table-column>
              <el-table-column label="类目" prop="cate_name"></el-table-column>
              <el-table-column label="分组" prop="group_name"></el-table-column>
              <el-table-column label="类别显示">
                <template slot-scope="scope">
                  <div class="type">
                    {{!scope.row.is_show_category?'是':'否'}}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="时间" prop="updatetime" width="110px"></el-table-column>
              <el-table-column label="操作" width="150px">
                  <template slot-scope="scope">
                    <div class="control">
                      <a @click="editGoods(scope.row.goods_id)">编辑</a>
                      <a v-show="currentType==='depot'||currentType==='soldout'" @click="handleClickShelves(scope.row,'sale')">上架</a>
                      <a v-show="currentType==='all'||currentType==='sale'" @click="handleClickShelves(scope.row,'depot ')">下架</a>
                      <a v-show="currentType==='sale' && scope.row.is_set_top==0" @click="setTop(scope.row, 1)">置顶</a>
                      <a v-show="currentType==='sale' && scope.row.is_set_top==1" @click="setTop(scope.row, 0)">取消置顶</a>
                      <a :href="scope.row.goods_url" target="_blank">查看来源</a>
                      <a v-show="currentType==='sale'" @click="checkPath(scope.row)">查看路径</a>
                      <a @click="handleClickDel(scope.row.goods_id,'delete')">删除</a>
                    </div>
                  </template>
              </el-table-column>
            </el-table>

          </div>
          <div class="pagination">
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page.sync="currentPage"
                :page-sizes="pageSizeArray"
                :page-size="10"
                layout="sizes, prev, pager, next"
                :total="totalCount">
              </el-pagination>
          </div>
          <el-dialog :show-close="false" :visible.sync="dialogVisible" width="1000px;">
            <div slot="title">
              <div class="dialog-title clearfix">
                <div class="titleName lf">将商品添加到分组</div>
                <div class="control-btns rf">
                  <span>是否在类别显示：</span>
                  <el-radio v-model="is_show_category" label="0">是</el-radio>
                  <el-radio v-model="is_show_category" label="1">否</el-radio>
                </div>
              </div>
            </div>
            <div>
              <el-tree
                :data="treeData"
                :default-checked-keys="defaultGroups"
                show-checkbox
                default-expand-all
                node-key="id"
                ref="tree"
                highlight-current
                :props="defaultProps">
              </el-tree>
            </div>
            <span slot="footer" class="dialog-footer clearfix">
              <div class="control-btns lf">
                <a @click="linktoNewGroup()" >新建分组</a>
                <a @click="linktoGroupList()" >管理分组</a>
              </div>
              <div class="rf">
                <el-button style="width:150px;" type="primary" @click="settledGroup()" >确 定</el-button>
                <el-button style="width:150px;" @click="dialogVisible = false">取 消</el-button>
              </div>
            </span>
          </el-dialog>
          <el-dialog :show-close="true" :visible.sync="showPathVisible" width="1000px;">
            <div slot="title">
              <div class="dialog-title clearfix" style="height:auto;border-bottom: none;">
                <div class="titleName lf" style="float:none">换购路径</div>
                <div class="titleName lf" style="float:none;font-size: 14px;line-height: 14px;">{{pathInfo.default_path}}</div>
              </div>
              <div class="dialog-title clearfix" style="height:auto;border-bottom: none;">
                <div class="titleName lf" style="float:none">兑换路径</div>
                <div class="titleName lf" style="float:none;font-size: 14px;line-height: 14px;">{{pathInfo.exchange_path}}</div>
              </div>
            </div>
          </el-dialog>
        </div>
      </div>
    </div>
</template>
<script>
export default {
  name: "goods",
  methods: {
    settledGroup() {
      let checkedNodes = this.$refs.tree.getCheckedNodes();
//      console.log("checkedNodes:",checkedNodes.length);
//      if (!checkedNodes.length) {
//        this.$message.error("请选择分组类别");
//        return;
//      }
      let groupId = [];
      let goodsId = [];
      for (let item of checkedNodes) {
        groupId.push(item.id);
      }
      for (let item of this.goodsArr) {
        goodsId.push(item.goods_id);
      }
      let formData = new FormData();
      formData.append("is_show_category", this.is_show_category);
      formData.append("group_ids", groupId.join(","));
      formData.append("goods_ids", goodsId.join(","));
      this.$http(
        "/wgl_admin/index.php?app=group&act=goods",
        "post",
        {},
        {},
        formData,
        success => {
          console.log(success);
          //重新获取列表数据
          this.getListData(this.currentType);
          this.$message.success("设置成功");
          this.dialogVisible = false;
        },
        error => {
          console.log(error);
          this.$message.error(error.state.msg);
        }
      );
    },

    //跳转到新建分组
    linktoNewGroup() {
      this.$router.push({
        name: "newGroup",
        params: {
          status: "new",
          targetId: "null"
        }
      });
    },
    //跳转到管理分组列表
    linktoGroupList() {
      this.$router.push({
        name: "category",
        params: {
          type: "2"
        }
      });
    },

    //编辑商品
    editGoods(targetId) {
      //跳转到商品详情页面
      this.$router.push({
        name: "goodsDetail",
        params: {
          goodsId: targetId
        }
      });
    },

    handleClickShelves(target, status) {
      let des = "";
      status === "sale" ? (des = "上架") : (des = "下架");
      console.log(target);
      if (!target.cate_name && status === "sale") {
        this.$message.error("该商品分类为空，不能上架");
        return;
      }
      this.$confirm("是否确定" + des + "该商品", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let ids = [];
          ids.push(target.goods_id);
          this.controlGoodsStatus(ids, status);
        })
        .catch(() => {});
    },

    //点击删除商品
    handleClickDel(targetId, status) {
      this.$confirm("是否确定删除该商品", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let ids = [];
          ids.push(targetId);
          this.controlGoodsStatus(ids, status);
        })
        .catch(() => {});
    },

    //批量上下架
    shelves(status) {
      if (!this.goodsArr.length) {
        this.$message.error("请选择需要操作的商品");
        return;
      }
      let des = "";
      status === "sale" ? (des = "上架") : (des = "下架");
      this.$confirm("是否确定" + des + "商品", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let ids = [];
          for (let item of this.goodsArr) {
            ids.push(item.goods_id);
          }
          this.controlGoodsStatus(ids, status);
        })
        .catch(() => {});
    },

    /*
    * @param ids  商品的数组
    * @param status 商品的状态
    * */
    controlGoodsStatus(ids, status) {
      let idStr = ids.join(",");
      let formData = new FormData();
      formData.append("ids", idStr);
      formData.append("status", status);
      this.$http(
        "/wgl_admin/index.php?app=goods&act=changeStatus",
        "post",
        {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        {},
        formData,
        success => {
          this.$message.success(success.state.msg);
          this.getListData("all");
        },
        error => {
          this.$message.error(error.state.msg);
          console.log(error);
        }
      );
    },

    //多选选择商品操作
    clickRow(selection) {
      this.goodsArr = selection;
    },

    //设置分组
    setGroup() {
      if (!this.goodsArr.length) {
        this.$message.error("请选择需要操作的商品");
        return;
      }
      if ( this.goodsArr ) {
        let goods_idArr = [];
        //console.log("选择了商品", this.goodsArr);
        for ( let item of this.goodsArr ){
          goods_idArr.push(item.goods_id);
        }
        this.goods_ids = goods_idArr.join(',');
        this.getGroupIdsList(this.goods_ids);
      }

      let validate = false;
      for (var i = 0; i < this.goodsArr.length; i++) {
        for (var j = i + 1; j < this.goodsArr.length; j++) {
          if (this.goodsArr[i].group_name !== this.goodsArr[j].group_name) {
            validate = true;
            break;
          }
        }
      }
      if (validate) {
        let self = this;
        this.$confirm("选择商品内有不一致的分组设置，请谨慎选择", "提示", {
          confirmButtonText: "继续",
          cancelButtonText: "放弃",
          type: "warning"
        })
          .then(() => {
            self.getGroupList();
            self.dialogVisible = true;
          })
          .catch(() => {});
      } else {
        this.getGroupList();
        this.dialogVisible = true;
      }
    },

    //获取分组列表
    getGroupList() {
      this.$http(
        "/wgl_admin/index.php?app=group&act=lists",
        "get",
        {},
        {},
        {},
        success => {
          console.log(success.data);
          let treeData = [];
          for (let parent of success.data) {
            let childArr = [];
            if (parent.child) {
              for (let children of parent.child) {
                let secondChild = [];
                if (children.child) {
                  for (let child of children.child) {
                    secondChild.push({
                      id: child.id,
                      label: child.name
                    });
                  }
                }
                childArr.push({
                  id: children.id,
                  label: children.name,
                  children: secondChild
                });
              }
            }
            treeData.push({
              id: parent.id,
              label: parent.name,
              children: childArr
            });
          }
          console.log(treeData);
          this.treeData = treeData;
        },
        error => {
          this.$message.error(error.state.msg);
        }
      );
    },

    //获取分组id列表
    getGroupIdsList(goods_ids) {
      this.$http(
        "/wgl_admin/index.php?app=group&act=get_goods_groups",
        "get",
        {},
        { ids: goods_ids },
        {},
        success => {
          console.log(success.data);
          console.log(success.data);
          this.defaultGroups = success.data.groups;
        },
        error => {
          this.$message.error(error.state.msg);
        }
      );
    },

    //默认获取分组列表
    getGroupListInit() {
      this.$http(
        "/wgl_admin/index.php?app=group&act=lists",
        "get",
        {},
        {},
        {},
        success => {
          let listData = success.data;
          let resArr = [];
          for (let item of listData) {
            let childArr = [];
            if (item.child) {
              for (let child of item.child) {
                childArr.push({
                  value: child.id,
                  label: child.name
                });
              }
            }
            resArr.push({
              value: item.id,
              label: item.name,
              children: childArr
            });
          }
          this.searchOptions = resArr;
        },
        error => {}
      );
    },

    //获取子分组所有内容
    getChildGroupById(id) {
      let promise = new Promise((resolve, reject) => {
        this.$http(
          "/wgl_admin/index.php?app=group&act=children",
          "get",
          {},
          { id: id },
          {},
          success => {
            // console.log(success);
          },
          error => {
            // console.log(error);
          }
        );
      });
      return promise;
    },

    //分页 每页条数切换
    handleSizeChange(data) {
      this.pageSize = data;
      this.getListData(this.currentType);
    },

    //分页
    handleCurrentChange() {
      console.log(this.currentPage);
      this.getListData(this.currentType);
    },


    //置顶
    setTop(data, status) {
      var formData = new FormData();
      formData.append("ids", data.goods_id + '');
      formData.append("status", status);
      this.$http(
        "/wgl_admin/index.php?app=goods&act=setTop",
        "post", {}, {}, formData,
        success => {
          this.getListData(this.currentType);
        },
        error => {
          this.$message.error(error.state.msg);
          console.log(error);
        }
      );
    },

    //获取列表数据
    getListData(status, page) {
      this.$http(
        "/wgl_admin/index.php?app=goods&act=getGoodsList",
        "get",
        {},
        {
          status: status,
          goods_name: this.goodsName,
          from: this.startTime,
          to: this.endTime,
          gtid: this.gtid[1]?this.gtid[1]:this.gtid[0],
          group_id: this.gpid[1]?this.gpid[1]:this.gpid[0],
          page: this.currentPage,
          per_page: this.pageSize
        },
        {},
        success => {
          this.goodsList = success.data.list;
          this.totalCount = success.data.total_count;
        },
        error => {
          this.$message.error(error.state.msg);
          console.log(error);
        }
      );
    },

    //查询操作
    searchData() {
      console.log(this.startTime);
      console.log(this.endTime);
      this.$http(
        "/wgl_admin/index.php?app=goods&act=getGoodsList",
        "get",
        {},
        {
          status: this.currentType,
          goods_name: this.goodsName,
          from: this.startTime,
          to: this.endTime,
          gtid: this.gtid[1]?this.gtid[1]:this.gtid[0],
          group_id: this.gpid[1]?this.gpid[1]:this.gpid[0],
          page: 1,
          per_page: this.pageSize
        },
        {},
        success => {
          this.currentPage = 1;
          this.goodsList = success.data.list;
          this.totalCount = success.data.total_count;
        },
        error => {
          console.log(error);
        }
      );
    },

    //获取商品的分类
    getCateList() {
      this.$http(
        "/wgl_admin/index.php?app=goods_cate&act=get_cate_list",
        "get",
        {},
        {},
        {},
        success => {
          let listData = success.data;
          let resArr = [];
          for (let item of listData) {
            let childArr = [];
            if (item.child) {
              for (let child of item.child) {
                childArr.push({
                  value: child.gtid,
                  label: child.cate_name
                });
              }
            }
            resArr.push({
              value: item.gtid,
              label: item.cate_name,
              children: childArr
            });
          }

          this.typeOptions = resArr;
        },
        error => {}
      );
    },
    /**
     * 查看路径
     */
    checkPath: function(row) {
      this.pathInfo = {
        default_path: row.default_path,
        exchange_path: row.exchange_path
      }
      this.showPathVisible = true;
    },
      //清空搜索条件、每页页码
    clearSearchData() {
        this.currentPage = 1;
        this.goodsName = "";
        this.gtid = [];
        this.gpid = [];
        this.endTime = "";
        this.startTime = "";
    }
    
  },
  watch: {
    $route(to, from) {
      this.$nextTick(() => {
        this.clearSearchData();
        this.currentType = to.params.type;
        console.log("路由变更");
        this.getListData(to.params.type);
      });
    }
  },
  components: {},
  created() {
    //获取列表数据
    this.getListData(this.currentType);
    this.getCateList();
    this.getGroupListInit();
  },
  mounted() {
  },
  data() {
    return {
      is_show_category: "1",
      dialogVisible: false,
      currentGoodsDetail: {},
      typeOptions: [], //分类属性
      goodsArr: [],
      defaultGroups: [],
      currentType: "all", //当前的分类类型
      totalCount: 0, //总页数
      currentPage: 1, //当前页码
      pageSize: 10, //每页条数
      pageSizeArray: PageSizeArray, //每页条数数组
      goodsList: [], //商品列表
      searchOptions: [], //所搜用的分组列表
      startTime: "",
      endTime: "",
      goodsName: "",
      goodsType: "",
      groupId: "",
      gtid: [],
      gpid: [],
      listData: [
        {
          name: "全部",
          type: "all",
          isActive: true
        },
        {
          name: "出售中",
          type: "sale",
          isActive: false
        },
        {
          name: "已售完",
          type: "soldout",
          isActive: false
        },
        {
          name: "仓储中",
          type: "depot",
          isActive: false
        }
      ],
      defaultProps: {
        children: "children",
        label: "label"
      },
      treeData: [],
      pathInfo: {},
      showPathVisible: false,
      changeOnSelect: true
    };
  }
};
</script>
<style lang="scss" scoped>
.goods-model {
  width: 100%;
  position: relative;
  padding-left: 118px;
  .view-box {
    .goods-list {
      padding: 30px 58px 30px 50px;
    }
    .btns {
      min-width: 1080px;
      margin-bottom: 38px;
    }
    .search-box {
      border: 1px solid #e6e8f4;
      max-width: 1466px;
      min-width: 1146px;
      width: 100%;
      height: 90px;
      padding: 25px 30px;
      .elInput {
        display: block;
        width: 120px;
        font-size: 12px;
        color: #333;
        margin-right: 20px;
      }
      .cascader {
        margin-right: 20px;
      }
      .labelName {
        height: 40px;
        line-height: 40px;
        color: #333;
        font-size: 14px;
      }
    }
    .table-box {
      width: 100%;
      max-width: 1466px;
      margin-top: 40px;
    }
    .pagination {
      max-width: 1466px;
      width: 100%;
      text-align: right;
      margin-top: 46px;
    }
  }


}
.control {
  .control-list > .action-btn {
    position: relative;
    color: #3f87f5;
    font-size: 12px;
    cursor: pointer;
    padding: 0 4px;
  }

  .control-list .action-btn:last-child {
    padding-right: 0;
  }

  .control-list .action-btn:last-child::after {
    width: 0;
  }

  .action-btn::after {
    position: absolute;
    top: 4px;
    right: -4px;
    content: "";
    width: 1px;
    height: 10px;
    background-color: #b7bdc9;
  }

}
.goodsDetail {
  > img {
    display: block;
    width: 54px;
    height: 54px;
    margin-right: 10px;
  }
  > span {
    text-align: left;
    width: 120px;
    word-wrap: break-word;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 4;
    overflow: hidden;
  }
}

.dialog-title {
  height: 70px;
  line-height: 70px;
  color: #333;
  border-bottom: 1px solid #e6e8f4;
  .titleName {
    font-size: 16px;
  }
  .control-btns {
    color: #e17474;
    font-size: 12px;
  }
}
.dialog-footer {
  display: block;
  height: 100%;
  width: 100%;
  padding-top: 18px;
  border-top: 1px solid #e6e8f4;
  .control-btns {
    font-size: 12px;
    color: #3f87f5;
    cursor: pointer;
    > a:first-child {
      margin-right: 40px;
    }
  }
}
</style>
